package com.newasia.server.common.checkHandler;

import com.newasia.server.common.exception.ValidateException;
import com.newasia.server.common.result.ManagementRetCode;
import com.newasia.server.common.tool.DateUtils;
import com.newasia.server.common.tool.SpringUtil;
import com.newasia.server.controller.form.UserForm;
import com.newasia.server.dal.entitys.LogPhoneCode;
import com.newasia.server.dal.entitys.LogPhoneCodeExample;
import com.newasia.server.dal.persistence.LogPhoneCodeMapper;

import java.util.List;

/**
 * @author LiChong
 * @description 验证码检测
 * @date 2020/4/2
 */

public class CodeCheckHandler extends CheckHandler {

    LogPhoneCodeMapper logPhoneCodeMapper = SpringUtil.getBean(LogPhoneCodeMapper.class);

    @Override
    public void doHandler(UserForm form) {
        Integer code = form.getCode();
        if (code.equals(""))
            throw new ValidateException(
                    ManagementRetCode.KAPTCHA_NOT_EXIST.getCode(),
                    ManagementRetCode.KAPTCHA_NOT_EXIST.getMessage()
            );
        LogPhoneCodeExample example = new LogPhoneCodeExample();
        example.createCriteria().andPhoneEqualTo(form.getMobile());
        example.setOrderByClause("expiration desc");
        List<LogPhoneCode> list = logPhoneCodeMapper.selectByExample(example);
        if (list.size()==0)
            throw new ValidateException(
                    ManagementRetCode.KAPTCHA_CODE_ERROR.getCode(),
                    ManagementRetCode.KAPTCHA_CODE_ERROR.getMessage());
        LogPhoneCode logPhoneCode = list.get(0);
        if(Integer.compare(logPhoneCode.getCode(),code)!=0)
            throw new ValidateException(
                    ManagementRetCode.KAPTCHA_CODE_ERROR.getCode(),
                    ManagementRetCode.KAPTCHA_CODE_ERROR.getMessage());
        //检测验证码是否已经被使用
        if(logPhoneCode.getIsverify()){
            throw new ValidateException(
                    ManagementRetCode.KAPTCHA_IS_USED.getCode(),
                    ManagementRetCode.KAPTCHA_IS_USED.getMessage());
        }
        //超时检测
        String expiration = logPhoneCode.getExpiration();
        if (DateUtils.dateSubtraction(expiration,DateUtils.getCurrentTime())>= 30*1000*60) {
            throw new ValidateException(
                    ManagementRetCode.KAPTCHA_OVER_TIME.getCode(),
                    ManagementRetCode.KAPTCHA_OVER_TIME.getMessage());
        }
        //通过检测后，将验证码状态设置为已使用
        logPhoneCode.setIsverify(true);
        logPhoneCodeMapper.updateByPrimaryKey(logPhoneCode);

        if(null != next) {
            next.doHandler(form);
        }
    }
}
